import React from "react";

export default class OuterClickExample extends React.Component {
    constructor(props) {
        super(props);

        this.state = {isOpen: false};
        //定义点击toggleContainer之外区域隐藏toggleContainer
        this.toggleContainer = React.createRef();
        this.onClickHandler = this.onClickHandler.bind(this);
        this.onClickOutsideHandler = this.onClickOutsideHandler.bind(this);
    }

    componentDidMount() {
        window.addEventListener('click', this.onClickOutsideHandler);
    }

    componentWillUnmount() {
        window.removeEventListener('click', this.onClickOutsideHandler);
    }

    onClickHandler() {
        this.setState(currentState => ({
            isOpen: !currentState.isOpen
        }));
    }

    onClickOutsideHandler(event) {
        if (this.state.isOpen && !this.toggleContainer.current.contains(event.target)) {
            this.setState({isOpen: false});
        }
    }

    render() {
        return (
            <React.Fragment>
                <h3>CLICKEXAMPLE</h3>
                <span  ref={this.toggleContainer} style={{'float': 'left', 'margin': '0 5px'}}>
                    <button onClick={this.onClickHandler}>Select</button>
                    {this.state.isOpen ?
                        (<ul>
                            <li>click 1</li>
                            <li>click 2</li>
                            <li>click 3</li>
                        </ul>) : null}
                </span>

            </React.Fragment>
        );
    }
}